package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.DyAnchorBo;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.IDyAnchorPhotoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.DyMemberCodeBo;
import com.ruoyi.system.domain.vo.DyMemberCodeVo;
import com.ruoyi.system.service.IDyMemberCodeService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 会员码Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-01
 */
@RequiredArgsConstructor
@Service
@Transactional(rollbackFor = Exception.class)
public class DyMemberCodeServiceImpl implements IDyMemberCodeService {

    private final DyMemberCodeMapper baseMapper;
    private final DyAnchorMapper dyAnchorMapper;
    private final DyOrderMapper dyOrderMapper;
    private final DyClientMapper dyClientMapper;
    private final DyClientAnchorMapper dyClientAnchorMapper;
    private final IDyAnchorPhotoService iDyAnchorPhotoService;
    @Resource
    private DyOrderServiceImpl dyOrderService;

    /**
     * 查询会员码
     */
    @Override
    public DyMemberCodeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询会员码列表
     */
    @Override
    public TableDataInfo<DyMemberCodeVo> queryPageList(DyMemberCodeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DyMemberCode> lqw = buildQueryWrapper(bo);
        lqw.orderByDesc(BaseEntity::getCreateTime);
        Page<DyMemberCodeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询会员码列表
     */
    @Override
    public List<DyMemberCodeVo> queryList(DyMemberCodeBo bo) {
        LambdaQueryWrapper<DyMemberCode> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DyMemberCode> buildQueryWrapper(DyMemberCodeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DyMemberCode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getPayUrl()), DyMemberCode::getPayUrl, bo.getPayUrl());
        lqw.eq(bo.getStatus() != null, DyMemberCode::getStatus, bo.getStatus());
        lqw.eq(bo.getAnchorId() != null, DyMemberCode::getAnchorId, bo.getAnchorId());
        return lqw;
    }

    /**
     * 新增会员码
     */
    @Override
    public Boolean insertByBo(DyMemberCodeBo bo) {
        DyMemberCode add = BeanUtil.toBean(bo, DyMemberCode.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改会员码
     */
    @Override
    public Boolean updateByBo(DyMemberCodeBo bo) {
        DyMemberCode update = BeanUtil.toBean(bo, DyMemberCode.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DyMemberCode entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除会员码
     */
    @Override
    public Boolean deleteWithValidByIds(List<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            if (CollUtil.isEmpty(ids)){
                throw new ServiceException("需要删除的数据为空");
            }
        }

        List<DyMemberCode> codes = baseMapper.selectList(new QueryWrapper<DyMemberCode>().lambda().in(DyMemberCode::getId, ids));
        if (CollUtil.isNotEmpty(codes)){

            for (DyMemberCode code : codes) {
                if (code.getPayType() == 0){
                    //微信 删除关联订单
                    dyOrderMapper.delete(new QueryWrapper<DyOrder>().lambda().eq(DyOrder::getTradeNo, code.getTradeNo()));
                }
            }
        }

        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public DyMemberCodeBo getMemberCodeInfo(DyMemberCodeBo bo) {
        if (bo == null || (bo.getId() == null && StringUtils.isEmpty(bo.getToken()))){
            throw new ServiceException("参数为空!");
        }

        DyMemberCode memberCode = baseMapper.selectOne(new LambdaQueryWrapper<DyMemberCode>()
                .eq(StringUtils.isNotEmpty(bo.getToken()), DyMemberCode::getToken, bo.getToken()).eq(bo.getId() != null, DyMemberCode::getId, bo.getId()));

        return BeanUtil.toBean(memberCode, DyMemberCodeBo.class);
    }

    @Override
    public DyMemberCode addMemberCode(DyMemberCodeBo bo) {

        List<DyMemberCode> codes = baseMapper.selectList(new QueryWrapper<DyMemberCode>().lambda().eq(DyMemberCode::getTradeNo, bo.getTradeNo()));
        if (CollUtil.isNotEmpty(codes)){
            throw new ServiceException("输入的订单号已被绑定");
        }
        if (bo.getPayType() == 1){
            List<DyOrder> orders = dyOrderMapper.selectList(new QueryWrapper<DyOrder>().lambda()
                    .eq(DyOrder::getTradeNo, bo.getTradeNo()));
            if (orders.isEmpty()){
                throw new ServiceException("输入的订单号不存在");
            }
        }

        DyAnchor anchor = dyAnchorMapper.selectById(bo.getAnchorId());

        if (bo.getPayType() == 0){
            //wx 生成订单
            DyOrder order = new DyOrder();
            order.setAmount(9900);
            order.setAnchorId(anchor.getId());
            order.setOrderNo(dyOrderService.buildOrderNo());
            order.setType(1L);
            order.setOrderStatus(1);
            order.setGoodsId(bo.getAnchorId());
            order.setGoodsName(anchor.getName());
            order.setTradeNo(bo.getTradeNo());
            dyOrderMapper.insert(order);

            bo.setOrderNo(order.getOrderNo());
        }

        bo.setStatus(0L);
        bo.setToken(IdUtil.simpleUUID());
        bo.setAnchorName(anchor.getName());
        DyMemberCode code = BeanUtil.toBean(bo, DyMemberCode.class);
        int i = baseMapper.insert(code);

        if (i < 1){
            throw new ServiceException("添加会员码失败");
        }

        return code;
    }

    @Override
    public int bindMemberCode(DyMemberCodeBo bo) {

        if (bo.getClientId() == null){
            throw new ServiceException("绑定用户数据不存在或已绑定");
        }

        DyMemberCode code = baseMapper.selectOne(new QueryWrapper<DyMemberCode>().lambda().eq(DyMemberCode::getToken, bo.getToken()));

        if (code == null){
            throw new ServiceException("会员码已失效");
        }

        DyClient client = dyClientMapper.selectById(bo.getClientId());

        if (client == null){
            throw new ServiceException("用户不存在");
        }

        DyClientAnchor dyClientAnchor = dyClientAnchorMapper.selectOne(
                new QueryWrapper<DyClientAnchor>().lambda().eq(DyClientAnchor::getClientId, client.getId())
                        .eq(DyClientAnchor::getToken, code.getToken()));

        if (dyClientAnchor != null && dyClientAnchor.getId() != null){
            return 1;
        }

        if (code.getStatus() != 0){
            throw new ServiceException("会员码已失效！");
        }

        DyClientAnchor one = dyClientAnchorMapper.selectOne(
                new QueryWrapper<DyClientAnchor>().lambda().eq(DyClientAnchor::getClientId, client.getId())
                        .eq(DyClientAnchor::getAnchorId, code.getAnchorId())
                        .eq(DyClientAnchor::getBuyType, 0));
        if (one != null){
            return 1;
        }

        DyAnchor anchor = dyAnchorMapper.selectById(code.getAnchorId());

        DyAnchorPhoto photo = iDyAnchorPhotoService.getNewestAnchorPhoto(code.getAnchorId());

        if (photo == null){
            photo = new DyAnchorPhoto();
            photo.setNewestTime(new Date());
        }

        DyClientAnchor clientAnchor = new DyClientAnchor();
        clientAnchor.setClientId(client.getId());
        clientAnchor.setAnchorId(anchor.getId());
        clientAnchor.setAnchorName(anchor.getName());
        clientAnchor.setCreateBy("admin");
        clientAnchor.setCreateTime(new Date());
        clientAnchor.setUpdateBy("admin");
        clientAnchor.setUpdateTime(new Date());
        clientAnchor.setToken(code.getToken());
        clientAnchor.setNewestTime(photo.getNewestTime());
        clientAnchor.setBuyType(0);

        dyClientAnchorMapper.insert(clientAnchor);

        code.setClientId(client.getId());
        code.setStatus(2L);
        return baseMapper.updateById(code);
    }
}
